#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#define COMMAND_SIZE 1024


const char* GetUserName()
{
    const char* name = getenv("USER");
    return name==NULL?"None":name;
}

const char* GetHostName()
{
    const char* name = getenv("HOSTNAME");
    return name==NULL?"None":name;
}

const char* GetPwd()
{
    const char* name = getenv("PWD");
    return name==NULL?"None":name;
}

void MakeCommandLine(char cmd_prompt[],int size)
{
    snprintf(cmd_prompt,size,"[%s@%s %s]#",GetUserName(),GetHostName(),GetPwd()); 
}

void PrintCommandPrompt()
{
    char prompt[COMMAND_SIZE];
    MakeCommandLine(prompt,sizeof(prompt));
    printf("%s",prompt);
    fflush(stdout);
}

bool GetCommandLine(char* out,int size)
{
    char* c = fgets(out,size,stdin);
    if(c == NULL)return false;
    out[strlen(out)-1]=0;//清理\n
    if(strlen(out)==0)return false;
    return true;
}

char* g_argv[128];
int g_argc = 0;

bool CommandParse(char* commandline)
{
    g_argc = 0;
    g_argv[g_argc++]=strtok(commandline," ");
    while((bool)(g_argv[g_argc++]=strtok(NULL," ")))//最后一个是NULL
    g_argc--;
    return true;
}

int main()
{
    while(1)
    {
        //1.输出命令行提示符
        PrintCommandPrompt();
        
        //2.获取用户输入的命令
        char commandline[COMMAND_SIZE];
        if(!GetCommandLine(commandline,sizeof(commandline)))
           continue;
        
        //3.命令行分析
        CommandParse(commandline);

        //4.执行命令
        pid_t id = fork();
        if(id == 0)
        {
            execvp(g_argv[0],g_argv);
            exit(1);
        }

        pid_t rid = waitpid(id,NULL,0);
        (void)rid;
    }

    return 0;
}
